using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Configuration;
using System.Collections;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using Microsoft.AceEngineering.SPM.SPMBusinessLayer;
using Microsoft.AceEngineering.SPM.SPMCustomDataEntity;

public partial class Admin_ManageScoreRanges : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["user"] == null)
            ValidateUser();
        else
        {
            UserCDE userData = (UserCDE)Session["user"];
            if (userData.Time.AddMinutes(Int32.Parse(ConfigurationManager.AppSettings["AbsoluteExpiration"].ToString())) <= DateTime.Now)
                ValidateUser();
        }

        bool isAdmin = UsersBL.GetUserAdmin(Session["loginname"].ToString());
        if (!isAdmin)
            Response.Redirect("~/Home.aspx");

        MaxThreshold();
    }

    private string GiveMeAlias(string domainAndAlias)
    {
        domainAndAlias = domainAndAlias.ToLower();
        char[] strSeperator = new char[] { '\\' };
        string[] aryAuthUser = new string[2];
        aryAuthUser = domainAndAlias.Split(strSeperator);
        return aryAuthUser[1];
    }

    private void ValidateUser()
    {
        string currAlias = GiveMeAlias(HttpContext.Current.User.Identity.Name);
        UserCDE user = UsersBL.ValidateUser(currAlias);
        if (user.Active)
        {
            Session["user"] = user;
            Session["loginname"] = user.UserAlias;
        }
        else
        {
            Response.Redirect(Request.ApplicationPath + "/Errors/NoAccess.htm");
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            string scoreName = string.Empty;
            int thValue = Int32.Parse(Server.HtmlEncode(txtThreshold.Text));
            try
            {
                scoreName = txtScoreName.Text.Trim();
                ScoreRangeBL.SaveNewScoreRange(scoreName, thValue, Session["loginname"].ToString());

                // Clear the range values.
                txtThreshold.Text = null;
                txtScoreName.Text = null;

                // Bind data again.
                gridScoreRanges.DataBind();
                MaxThreshold();
            }
            catch (Exception ex)
            {
                string strErrorType = ex.Message.ToString().Substring(0, 8);

                Page pge = (Page)this.Page;
                Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(ex, Request.IsLocal, pge, Session, Request);
                if (!Request.IsLocal && strErrorType != "APMError")
                {
                    Server.ClearError();
                    Server.Transfer(Request.ApplicationPath + "/Errors/GenericErrorPage.htm");
                }
            }
        }
        else
        {
            StringBuilder msg = new StringBuilder("Please correct the following:\\n");
            // Loop through all validation controls to see which
            // generated the errors.
            foreach (IValidator aValidator in this.Validators)
            {
                if (!aValidator.IsValid)
                {
                    msg.Append("- " + aValidator.ErrorMessage + "\\n");
                }
            }
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg.ToString(), "errorkey");
        }
    }

    protected void Grid_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {
        if (e.Exception != null)
        {
            string strErrorType = e.Exception.InnerException.Message.Substring(0, 8);

            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(e.Exception.InnerException, Request.IsLocal, pge, Session, Request);
            if (!Request.IsLocal && strErrorType != "APMError")
            {
                Server.ClearError();
                Server.Transfer(Request.ApplicationPath + "/Errors/GenericErrorPage.htm");
            }
            else
            {
                e.KeepInEditMode = true;
                e.ExceptionHandled = true;
            }
        }
    }

    protected void MaxThreshold()
    {
        int[] max = ScoreRangeBL.GetQuestionMaxAnswerWts();
        int maxTotal = max[0];
        int maxThreshold = max[1];

        if (maxTotal > maxThreshold)
        {
            txtThreshold.Text = maxTotal.ToString();
            txtThreshold.Enabled = false;
            pnlError.Visible = true;
        }
        else
        {
            txtThreshold.Enabled = true;
            pnlError.Visible = false;
        }
    }

    protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        foreach (System.Web.UI.Control BaseControl in e.Row.Cells[0].Controls)
        {
            if (BaseControl.GetType().BaseType == typeof(LinkButton))
            {
                LinkButton linkBtn = (LinkButton)BaseControl;
                if (linkBtn.CommandName == "Delete")
                    linkBtn.OnClientClick = "return confirm('Are you sure you want to delete this Score Range?');";
            }
        }
    }


    protected void Grid_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {
        if (e.Exception != null)
        {
            string strErrorType = e.Exception.InnerException.Message.Substring(0, 8);

            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(e.Exception.InnerException, Request.IsLocal, pge, Session, Request);
            if (!Request.IsLocal && strErrorType != "APMError")
            {
                Server.ClearError();
                Server.Transfer(Request.ApplicationPath + "/Errors/GenericErrorPage.htm");
            }
            else
            {
                e.ExceptionHandled = true;
            }
        }
        else
        {
            int rows = gridScoreRanges.Rows.Count;

            if (rows == 1 && gridScoreRanges.PageIndex > 0)
                gridScoreRanges.PageIndex = gridScoreRanges.PageIndex - 1;
        }
        MaxThreshold();
    }
}
